<template>
  <view>
    <uni-section title="外勤签到" type="line" padding>
      <uni-forms ref="baseForm" labelWidth="80px">
        <uni-forms-item label="出门打卡" required>
          <button class="mini-btn" size="mini" @click="mornongOut" :disabled="signs.morningcheckout" :loading="loading"
                  :type="signs.morningcheckout ? 'default': 'primary'">上午出门
          </button>
          &nbsp;
          <button class="mini-btn" size="mini" @click="afterOut" :disabled="signs.afternooncheckout" :loading="loading"
                  :type="signs.afternooncheckout ? 'default': 'primary'">下午出门
          </button>
        </uni-forms-item>

        <uni-forms-item label="返回打卡" required>
          <button class="mini-btn" size="mini" @click="morningBack" :disabled="signs.morningcheckin" :loading="loading"
                  :type="signs.morningcheckin ? 'default': 'primary'">上午返回
          </button>
          &nbsp;
          <button class="mini-btn" size="mini" @click="afterBack" :disabled="signs.afternooncheckin" :loading="loading"
                  :type="signs.afternooncheckin ? 'default': 'primary'">下午返回
          </button>
        </uni-forms-item>
      </uni-forms>
    </uni-section>

    <uni-section title="今日拜访计划" type="line">
      <uni-card :title="item.unitName" padding="10px 0" v-for="(item, index) in visiters" :index="index" :key="index">
        <view slot="actions" class="card-actions no-border">
          <view class="card-actions-item" @click="arriveClick(item)">
            <button size="mini" class="card-actions-item-text" :type="item.arriveTime ? 'default' : 'primary'" :loading="loading"
                    :disabled="item.arriveTime">到达签到
            </button>
          </view>
          <view class="card-actions-item" @click="serviceClick(item)">
            <button size="mini" class="card-actions-item-text" :type="item.serviceTime ? 'default' : 'primary'" :loading="loading"
                    :disabled="item.serviceTime">服务展示
            </button>
          </view>
          <view class="card-actions-item" @click="leaveClick(item)">
            <button size="mini" class="card-actions-item-text" :type="item.leaveTime ? 'default' : 'primary'" :loading="loading"
                    :disabled="item.leaveTime">离开签到
            </button>
          </view>
        </view>
      </uni-card>
    </uni-section>
  </view>
</template>

<script>
import {reactive, ref} from "vue";
import CameraSettingsComponent from "@/components/watermark-camera/CameraSettingsComponent.vue";
import {ViewModel} from "./ViewModel";
export default {
  components: {CameraSettingsComponent},
  setup() {
    const showCameraSettings = ref(false);
    const splitLogos = ref([]);
    const viewModel = reactive(new ViewModel());
    return {
      showCameraSettings: showCameraSettings,
      splitLogos: splitLogos,
      viewModel: viewModel,
    };
  },
  data() {
    return {
      loading: false,
      imageUrl: null,
      signs: {},
      visiters: [],
    }
  },
  onShow() {
    this.loadList();
    this.loadSign();
  },
  methods: {
    mornongOut() {
      this.validAndSetUserInfo("外勤：上午出门", 4, 1, '71ab0d62-9f08-4ac9-9fd2-b0c879cf7761');
    },
    morningBack() {
      this.validAndSetUserInfo("外勤：上午返回", 5, 1, 'b51661d8-d4c8-4c50-9aa3-4d09204fa32e');
    },
    afterOut() {
      this.validAndSetUserInfo("外勤：下午出门", 6, 1, 'e4ec6b57-f23b-4d1a-9f4b-81df093c6332');
    },
    afterBack() {
      this.validAndSetUserInfo("外勤：下午返回", 7, 1, 'e2b10565-7c68-4ffd-8806-a33005ab52f5');
    },
    arriveClick(item) {
      this.validAndSetUserInfo(item.unitName, 1, item.planID, item.waterMarkID)
    },
    serviceClick(item) {
      this.validAndSetUserInfo(item.unitName, 2, item.planID, item.waterMarkID)
    },
    leaveClick(item) {
      this.validAndSetUserInfo(item.unitName, 3, item.planID, item.waterMarkID)
    },
    async takePhoto(title, type, id, waterMarkID) {
      this.loading = true;
      uni.request({
        url: '/api/camera/config',
        dataType: 'json',
        success: (res) => {
          let resData = res.data.data;
          console.log('request success', res.data.data);
          let camera = new XHeyCamera({
            // 是否需要关闭拍照确认
            disablePhotoConfirm: false,
            // 开启自定义水印编辑
            enableCustomWatermark: false,
            // 【必须】应用 ID (替换为你的应用 ID)
            appid: resData.appid,
            timestamp: resData.timestamp,
            noncestr: resData.noncestr,
            signature: resData.signature,
            watermarkId: waterMarkID,
            maxImageCount: 1,
            enableLogMessage: true,
            updateViewportTag: true,
            watermarkScale: this.viewModel.watermarkScale,
            disableOffcialWatermark: true,
            disableWatermarkDragging: true,
            isFromH5Demo: true,
            customInputItems: {
              "姓名": sessionStorage.getItem("userName"),
              "手机号码": sessionStorage.getItem("phone")
            }
          });
          // 测试服务器地址
          camera.url = "https://sdk-h5.xhey.top";
          camera.onSuccess((imageBase64Data, userCommentObject) => {
            this.imageUrl = imageBase64Data;
            // 上传图片
            this.loading = true;
            uni.request({
              method: 'POST',
              url: '/api/camera/uploadFile',
              data: {
                file: imageBase64Data,
                fileName: "/images/" + new Date().getTime(),
                type: type,
                busId: id
              },
              header: {
                'Content-Type': 'application/json' // 默认值，可省略
              },
              success: (res) => {
                uni.showToast({
                  title: '操作成功',
                  icon: 'none'
                });

                this.loadList();
                this.loadSign();
              },
              fail: (err) => {
                console.log('request fail', err);
                uni.showModal({
                  content: err.errMsg,
                  showCancel: false
                });
              },
              complete: () => {
                this.loading = false;
              }
            });
          });
          camera.onCaptureStillImages((imageBase64DataArray) => {
            console.log("拍照成功:", imageBase64DataArray);
            this.splitLogos = imageBase64DataArray.map((imageBase64Data) => [
              {url: imageBase64Data},
            ]);
          });
          camera.onCancel(() => {
            console.log("取消操作");
          });
          camera.onError((error) => {
            console.error("错误:", error);
          });
          camera.onLogInfo((message) => {
            console.log(message);
          });
          camera.onLogError((message) => {
            console.error(message);
          });
          camera.onLogWarn((message) => {
            console.warn(message);
          });
          camera.takePhoto();
        },
        complete: () => {
          this.loading = false;
        }
      });
    },
    async validAndSetUserInfo(title, type, id, waterMarkID) {
      uni.request({
        url: '/api/sysUser/me',
        data: {},
        success: (res) => {
          console.log(res.statusCode)
          if (res.statusCode === 200) {
            console.log(res.data.data);
            sessionStorage.setItem("userName", res.data.data.realName);
            sessionStorage.setItem("phone", res.data.data.mobile);
            this.takePhoto(title, type, id, waterMarkID)
          } else {
            uni.showToast({
              title: '用户信息获取失败',
              icon: 'none'
            });
          }

          if (res.statusCode === 401) {
            uni.showModal({
              content: "请登录",
              showCancel: false
            });
            setTimeout(() => {
              uni.navigateTo({
                url: '/pages/login/login'
              });
            }, 500)
          }
        }
      });
    },
    loadList() {
      uni.request({
        url: '/api/camera/servicePlan',
        data: {},
        success: (res) => {
          if (res.statusCode === 200) {
            this.visiters = res.data.data;
          }

          if (res.statusCode === 401) {
            uni.showModal({
              content: "请登录",
              showCancel: false
            });
            setTimeout(() => {
              uni.navigateTo({
                url: '/pages/login/login'
              });
            }, 500)
          }
        }
      });
    },
    loadSign() {
      uni.request({
        url: '/api/camera/signRecord',
        success: (res) => {
          if (res.statusCode === 200) {
            this.signs = res.data.data;
          }
        }
      });
    }
  }
}
</script>

<style lang="scss">
.container {
  overflow: hidden;
}

.custom-cover {
  flex: 1;
  flex-direction: row;
  position: relative;
}

.cover-content {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 40px;
  background-color: rgba($color: #000000, $alpha: 0.4);
  display: flex;
  flex-direction: row;
  align-items: center;
  padding-left: 15px;
  font-size: 14px;
  color: #fff;
}

.card-actions {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  height: 45px;
  border-top: 1px #eee solid;
}

.card-actions-item {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.card-actions-item-text {
  font-size: 12px;
  color: #ffffff;
  margin-left: 5px;
}

.cover-image {
  flex: 1;
  height: 150px;
}

.no-border {
  border-width: 0;
}
</style>
